//
//  BannerDetailWebVc.m
//  New_Runway
//
//  Created by mack on 2018/2/28.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "BannerDetailWebVc.h"
@interface NSURLRequest (InvalidSSLCertificate)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;

@end
@interface BannerDetailWebVc ()<UIActionSheetDelegate>
@property (nonatomic, strong) NSURLRequest *request;
//判断是否是HTTPS的
@property (nonatomic, assign) BOOL isAuthed;

//返回按钮
@property (nonatomic, strong) UIButton *backItem;
//关闭按钮
@property (nonatomic, strong) UIButton *closeItem;

//下面的三个属性是添加进度条的
@property (nonatomic, assign) BOOL theBool;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation BannerDetailWebVc

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = kColorWhite();
    self.navigationBarView.titleLabel.text = self.title;
    if ([WXApi isWXAppInstalled]) {
        [self.navigationBarView.rightItem setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    }else{
        self.navigationBarView.rightItem.hidden = YES;
    }
    self.wkwebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.navH, self.view.frame.size.width, self.view.frame.size.height - self.BotH - self.navH)];
    self.wkwebView.navigationDelegate = self;
    [self.view addSubview:self.wkwebView];
    [self addProgressBar];
    [self loadHTML:self.url];
    
}
-(void)rightItemClick{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"微信",@"朋友圈", nil ];
    [sheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self shareToWechat:0];
    }else if (buttonIndex == 1){
        [self shareToWechat:1];
    }
    
}

-(void)shareToWechat:(NSInteger)tag{
    
   
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText               = NO;
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = self.title;//分享标题
//    urlMessage.description = @"";//分享描述
//    if ([self.imageUrl isEqualToString:@""]) {
        [urlMessage setThumbImage:[UIImage imageNamed:@"LOGO"]];
//    }else{
//
//        [urlMessage setThumbImage:[self getImageFromURL:self.imageUrl]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
//    }
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = self.url;//分享链接
    urlMessage.mediaObject = webObj;
    req.message = urlMessage;
    // 目标场景
    // 发送到聊天界面  WXSceneSession
    // 发送到朋友圈    WXSceneTimeline
    // 发送到微信收藏  WXSceneFavorite
    if (tag == 0) {
        req.scene = WXSceneSession;
    }else{
        req.scene = WXSceneTimeline;
    }
    [WXApi sendReq:req];
}
-(UIImage *) getImageFromURL:(NSString *)fileURL
{
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    return result;
}
- (void)addProgressBar
{
    // 仿微信进度条
    CGFloat progressBarHeight = 0.5f;
    
    
    //    CGRect navigationBarBounds = self.navigationBarView.bounds;
    CGRect barFrame = CGRectMake(0, self.navH, Screen_width, progressBarHeight);
    self.progressView = [[UIProgressView alloc] initWithFrame:barFrame];
    self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    self.progressView.trackTintColor = MAIN_NAV_COLOR(); //背景色
    self.progressView.progressTintColor = kColorWhite(); //进度色
    [self.view addSubview:self.progressView];
}

//加载URL
- (void)loadHTML:(NSString *)htmlString
{
    NSURL *url = [NSURL URLWithString:htmlString];
    self.request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
    [self.wkwebView loadRequest:self.request];
    
}
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
 
    NSString *scheme = [[navigationAction.request URL] scheme];
   
    if ([scheme isEqualToString:@"https"]) {
        //如果是https:的话，那么就用NSURLConnection来重发请求。从而在请求的过程当中吧要请求的URL做信任处理。
        if (!self.isAuthed) {
            NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:navigationAction.request delegate:self];
            [conn start];
            [webView stopLoading];
            //            decisionHandler(YES);
        }
    }
    decisionHandler(YES);
}

#pragma mark ================= NSURLConnectionDataDelegate <NSURLConnectionDelegate>

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
        self.isAuthed = YES;
        //NSURLCredential 这个类是表示身份验证凭据不可变对象。凭证的实际类型声明的类的构造函数来确定。
        NSURLCredential *cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:cre forAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"网络不给力");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.isAuthed = YES;
    //webview 重新加载请求。
    [self.wkwebView loadRequest:self.request];
    [connection cancel];
}
//- (void)closeNative
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
//- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
//{
//
//    if ([message.name isEqualToString:@"finish"]) {
//
//
//    }
//}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    self.progressView.progress = 0;
    self.theBool = false;
    //0.01667 is roughly 1/60, so it will update at 60 FPS
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01667 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
}
//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    self.theBool = true; //加载完毕后，进度条完成
    //执行Js
    kSelfWeak;
    NSString *inputValueJS = @"document.title";
    //执行Js
    [webView evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
        weakSelf.title = response;
    }];
    
    
}
- (void)timerCallback
{
    if (self.theBool) {
        if (self.progressView.progress >= 1) {
            self.progressView.hidden = true;
            [self.timer invalidate];
        } else {
            self.progressView.progress += 0.1;
        }
    } else {
        self.progressView.progress += 0.1;
        if (self.progressView.progress >= 0.9) {
            self.progressView.progress = 0.9;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //移除progressView  because UINavigationBar is shared with other ViewControllers
    [self.progressView removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
